#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
视力记录日志模型
"""

from datetime import datetime
import json
import enum
from sqlalchemy import Column, Integer, String, Text, DateTime, Enum, text
from sqlalchemy.orm import relationship
from backend.infrastructure.database import db

class LogAction(enum.Enum):
    """日志操作类型枚举 - 使用大写值匹配数据库"""
    CREATE = "CREATE"       # 创建记录
    UPDATE = "UPDATE"       # 更新记录  
    DELETE = "DELETE"       # 删除记录
    RESTORE = "RESTORE"     # 恢复记录

class VisionRecordLog(db.Model):
    """视力记录操作日志表"""
    __tablename__ = 'vision_record_logs'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    record_id = Column(Integer, nullable=False, comment='关联的视力记录ID')
    student_id = Column(Integer, nullable=False, comment='学生ID')
    action = Column(Enum(LogAction), nullable=False, comment='操作类型')
    operator = Column(String(100), nullable=False, comment='操作人')
    operation_time = Column(DateTime, default=datetime.now, comment='操作时间')
    old_content = Column(Text, comment='修改前的数据(JSON格式)')
    new_content = Column(Text, comment='修改后的数据(JSON格式)')
    operation_desc = Column(String(500), comment='操作描述')
    ip_address = Column(String(50), comment='操作IP地址')
    user_agent = Column(String(500), comment='用户代理')
    created_at = Column(DateTime, default=datetime.now, comment='日志创建时间')
    
    @classmethod
    def log_create(cls, record, operator='系统', ip_address=None):
        """记录创建操作日志"""
        try:
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action=LogAction.CREATE,
                operator=operator,
                operation_time=datetime.now(),
                new_content=json.dumps(record.to_dict(), ensure_ascii=False, default=str),
                operation_desc=f'创建视力记录 - 测量日期: {record.measure_date}',
                ip_address=ip_address
            )
            db.session.add(log)
            return log
        except Exception as e:
            print(f"创建日志失败: {e}")
            return None
    
    @classmethod
    def log_update(cls, record, old_data, operator='系统', ip_address=None):
        """记录更新操作日志"""
        try:
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action=LogAction.UPDATE,
                operator=operator,
                operation_time=datetime.now(),
                old_content=json.dumps(old_data, ensure_ascii=False, default=str),
                new_content=json.dumps(record.to_dict(), ensure_ascii=False, default=str),
                operation_desc=f'更新视力记录 - 测量日期: {record.measure_date}',
                ip_address=ip_address
            )
            db.session.add(log)
            return log
        except Exception as e:
            print(f"更新日志失败: {e}")
            return None
    
    @classmethod
    def log_delete(cls, record, operator='系统', ip_address=None):
        """记录删除操作日志"""
        try:
            log = cls(
                record_id=record.id,
                student_id=record.student_id,
                action=LogAction.DELETE,
                operator=operator,
                operation_time=datetime.now(),
                old_content=json.dumps(record.to_dict(), ensure_ascii=False, default=str),
                operation_desc=f'删除视力记录 - 测量日期: {record.measure_date}',
                ip_address=ip_address
            )
            db.session.add(log)
            return log
        except Exception as e:
            print(f"删除日志失败: {e}")
            return None
    
    @classmethod
    def log_restore(cls, record_id, student_id, old_data, restored_data, operator='系统', ip_address=None):
        """记录恢复操作日志
        
        Args:
            record_id: 记录ID
            student_id: 学生ID  
            old_data: 恢复前的数据状态
            restored_data: 恢复后的数据状态
            operator: 操作人
            ip_address: IP地址
        """
        try:
            log = cls(
                record_id=record_id,
                student_id=student_id,
                action=LogAction.RESTORE,
                operator=operator,
                operation_time=datetime.now(),
                old_content=json.dumps(old_data, ensure_ascii=False, default=str),
                new_content=json.dumps(restored_data, ensure_ascii=False, default=str),
                operation_desc=f'恢复视力记录 - 记录ID: {record_id}',
                ip_address=ip_address
            )
            db.session.add(log)
            return log
        except Exception as e:
            print(f"恢复日志失败: {e}")
            return None
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'record_id': self.record_id,
            'student_id': self.student_id,
            'action': self.action.value if self.action else None,  # type: ignore
            'operator': self.operator,
            'operation_time': self.operation_time.strftime('%Y-%m-%d %H:%M:%S') if self.operation_time else None,  # type: ignore
            'old_content': self.old_content,
            'new_content': self.new_content,
            'operation_desc': self.operation_desc,
            'ip_address': self.ip_address,
            'user_agent': self.user_agent,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None  # type: ignore
        }
